<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="第8篇：高级数据类型之列表, 张亚飞,飞凡空间,国学,Python,Go">
    <meta name="description" content="基础数据类型：

int，整数类型（整形）
float，浮点类型（浮点型）
complex,复数类型
bool，布尔类型
str，字符串类型

高级数据类型：

list，列表类型
tuple，元组类型
dict，字典类型
set，集合类型">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
	<meta name="baidu-site-verification" content="code-w2ezfaoXE0" />
    <title>第8篇：高级数据类型之列表 | 飞凡空间</title>
    <link rel="icon" type="image/png" href="/medias/my-logo.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">
    
    <script src="/libs/jquery/jquery.min.js"></script>
    
<meta name="generator" content="Hexo 5.2.0">
<style>.github-emoji { position: relative; display: inline-block; width: 1.2em; min-height: 1.2em; overflow: hidden; vertical-align: top; color: transparent; }  .github-emoji > span { position: relative; z-index: 10; }  .github-emoji img, .github-emoji .fancybox { margin: 0 !important; padding: 0 !important; border: none !important; outline: none !important; text-decoration: none !important; user-select: none !important; cursor: auto !important; }  .github-emoji img { height: 1.2em !important; width: 1.2em !important; position: absolute !important; left: 50% !important; top: 50% !important; transform: translate(-50%, -50%) !important; user-select: none !important; cursor: auto !important; } .github-emoji-fallback { color: inherit; } .github-emoji-fallback img { opacity: 0 !important; }</style>
<link rel="alternate" href="/atom.xml" title="飞凡空间" type="application/atom+xml">
<link rel="stylesheet" href="/css/prism-tomorrow.css" type="text/css">
<link rel="stylesheet" href="/css/prism-line-numbers.css" type="text/css"></head>


<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/my-logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">飞凡空间</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友情链接</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/contact" class="waves-effect waves-light">
      
      <i class="fas fa-comments" style="zoom: 0.6;"></i>
      
      <span>留言板</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>

<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/my-logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">飞凡空间</div>
        <div class="logo-desc">
            
            诚者，天之道也；诚之者，人之道也。诚者，不勉而中，不思而得。从容中道，圣人也；诚之者，择善而固执者也。
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友情链接
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-comments"></i>
			
			留言板
		</a>
          
        </li>
        
        
    </ul>
</div>

        </div>

        
    </nav>

</header>

    



<div class="bg-cover pd-header post-cover" style="background-image: url('https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=3901619598,3968112057&fm=26&gp=0.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <div class="description center-align post-title">
                        第8篇：高级数据类型之列表
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        margin: 35px 0 15px 0;
        padding-left: 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #toc-content .is-active-link::before {
        background-color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/Python%E4%B9%8B%E8%B7%AF/">
                                <span class="chip bg-color">Python之路</span>
                            </a>
                        
                            <a href="/tags/%E9%AB%98%E7%BA%A7%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B/">
                                <span class="chip bg-color">高级数据类型</span>
                            </a>
                        
                            <a href="/tags/%E5%88%97%E8%A1%A8/">
                                <span class="chip bg-color">列表</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/Python/" class="post-category">
                                Python
                            </a>
                        
                            <a href="/categories/Python/base/" class="post-category">
                                base
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2020-12-15
                </div>
                

                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>文章字数:&nbsp;&nbsp;
                    5.6k
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-clock fa-fw"></i>阅读时长:&nbsp;&nbsp;
                    22 分
                </div>
                
				
                
                    <div id="busuanzi_container_page_pv" class="info-break-policy">
                        <i class="far fa-eye fa-fw"></i>阅读次数:&nbsp;&nbsp;
                        <span id="busuanzi_value_page_pv"></span>
                    </div>
				
            </div>
            
        </div>
        <hr class="clearfix">
        <div class="card-content article-card-content">
            <div id="articleContent">
                <p>基础数据类型：</p>
<ul>
<li><span style="color:gray">int，整数类型（整形）</span></li>
<li><span style="color:gray">float，浮点类型（浮点型）</span></li>
<li><span style="color:gray">complex,复数类型</span></li>
<li><span style="color:gray">bool，布尔类型</span></li>
<li><span style="color:gray">str，字符串类型</span></li>
</ul>
<p>高级数据类型：</p>
<ul>
<li><strong>list，列表类型</strong></li>
<li><span style="color:gray">tuple，元组类型</span></li>
<li><span style="color:gray">dict，字典类型</span></li>
<li><span style="color:gray">set，集合类型</span></li>
</ul>
<p><strong>学习目标：掌握列表的各种操作</strong></p>
<p><strong>本节问题</strong>：</p>
<ul>
<li>问题1：列表的定义是什么？有哪些特点？</li>
<li>问题2：列表支持哪些方法和运算？</li>
<li>问题3：列表如何对元素进行增删改查？列出具体的方法或者基于的运算。</li>
<li>问题4：如何对列表元素进行遍历？</li>
<li>问题5：列表生成式和生成器的语法是什么？简单说一下它们的区别。</li>
</ul>
<p>不知道大家是否注意到，字符串类型（<code>str</code>）和之前讲到的数值类型（<code>int</code>和<code>float</code>）有一些区别。数值类型是标量类型，也就是说这种类型的对象没有可以访问的内部结构；而字符串类型是一种结构化的、非标量类型，所以才会有一系列的属性和方法。接下来我们要介绍的列表（<code>list</code>），也是一种结构化的、非标量类型，它是值的有序序列，每个值都可以通过索引进行标识，定义列表可以将列表的元素放在<code>[]</code>中，多个元素用<code>,</code>进行分隔，可以使用<code>for</code>循环对列表元素进行遍历，也可以使用<code>[]</code>或<code>[:]</code>运算符取出列表中的一个或多个元素。</p>
<h2 id="案例引入"><a href="#案例引入" class="headerlink" title="案例引入"></a>案例引入</h2><p>在开始本节课的内容之前，我们先给大家一个编程任务，将一颗色子掷6000次，统计每个点数出现的次数。这个任务对大家来说应该是非常简单的，我们可以用1到6均匀分布的随机数来模拟掷色子，然后用6个变量分别记录每个点数出现的次数，相信大家都能写出下面的代码。</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token keyword">import</span> random

f1 <span class="token operator">=</span> <span class="token number">0</span>
f2 <span class="token operator">=</span> <span class="token number">0</span>
f3 <span class="token operator">=</span> <span class="token number">0</span>
f4 <span class="token operator">=</span> <span class="token number">0</span>
f5 <span class="token operator">=</span> <span class="token number">0</span>
f6 <span class="token operator">=</span> <span class="token number">0</span>
<span class="token keyword">for</span> _ <span class="token keyword">in</span> range<span class="token punctuation">(</span><span class="token number">6000</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
    face <span class="token operator">=</span> random<span class="token punctuation">.</span>randint<span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">6</span><span class="token punctuation">)</span>
    <span class="token keyword">if</span> face <span class="token operator">==</span> <span class="token number">1</span><span class="token punctuation">:</span>
        f1 <span class="token operator">+=</span> <span class="token number">1</span>
    <span class="token keyword">elif</span> face <span class="token operator">==</span> <span class="token number">2</span><span class="token punctuation">:</span>
        f2 <span class="token operator">+=</span> <span class="token number">1</span>
    <span class="token keyword">elif</span> face <span class="token operator">==</span> <span class="token number">3</span><span class="token punctuation">:</span>
        f3 <span class="token operator">+=</span> <span class="token number">1</span>
    <span class="token keyword">elif</span> face <span class="token operator">==</span> <span class="token number">4</span><span class="token punctuation">:</span>
        f4 <span class="token operator">+=</span> <span class="token number">1</span>
    <span class="token keyword">elif</span> face <span class="token operator">==</span> <span class="token number">5</span><span class="token punctuation">:</span>
        f5 <span class="token operator">+=</span> <span class="token number">1</span>
    <span class="token keyword">else</span><span class="token punctuation">:</span>
        f6 <span class="token operator">+=</span> <span class="token number">1</span>

<span class="token keyword">print</span><span class="token punctuation">(</span>f<span class="token string">'1点出现了{f1}次'</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>f<span class="token string">'2点出现了{f2}次'</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>f<span class="token string">'3点出现了{f3}次'</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>f<span class="token string">'4点出现了{f4}次'</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>f<span class="token string">'5点出现了{f5}次'</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>f<span class="token string">'6点出现了{f6}次'</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>看看上面的代码，相信大家一定觉得它非常的“笨重”和“丑陋”，更可怕的是，如果要统计掷2颗或者更多的色子统计每个点数出现的次数，那就需要定义更多的变量，写更多的分支结构。讲到这里，相信大家一定想问：有没有办法用一个变量来保存多个数据，有没有办法用统一的代码对多个数据进行操作？答案是肯定的，在Python中我们可以通过容器类型的变量来保存和操作多个数据，我们首先为大家介绍列表（list）这种新的数据类型。</p>
<h2 id="列表的定义"><a href="#列表的定义" class="headerlink" title="列表的定义"></a>列表的定义</h2><p>在Python中，<strong>列表是由一系元素按特定顺序构成的数据序列</strong>，这样就意味着定义一个列表类型的变量，<strong>可以保存多个数据</strong>，而且<strong>允许有重复的数据</strong>。跟我们讲到的字符串类型一样，列表也是一种结构化的、非标量类型。</p>
<p>在Python中，可以使用<code>[]</code>字面量语法来定义列表，列表中的多个元素用逗号进行分隔，代码如下所示。</p>
<pre class="line-numbers language-python"><code class="language-python">items0 <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token punctuation">]</span> <span class="token comment" spellcheck="true"># 空列表</span>
items1 <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token number">35</span><span class="token punctuation">,</span> <span class="token number">12</span><span class="token punctuation">,</span> <span class="token number">99</span><span class="token punctuation">,</span> <span class="token number">68</span><span class="token punctuation">,</span> <span class="token number">55</span><span class="token punctuation">,</span> <span class="token number">87</span><span class="token punctuation">]</span>
items2 <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token string">'Python'</span><span class="token punctuation">,</span> <span class="token string">'Java'</span><span class="token punctuation">,</span> <span class="token string">'Go'</span><span class="token punctuation">,</span> <span class="token string">'Kotlin'</span><span class="token punctuation">]</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<p>除此以外，还可以通过Python内置的<code>list</code>函数将其他序列变成列表。准确的说，<code>list</code>并不是一个函数，而是创建列表对象的构造器（后面会讲到对象和构造器这两个概念）。</p>
<pre class="line-numbers language-python"><code class="language-python">items0 <span class="token operator">=</span> list<span class="token punctuation">(</span><span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># 空列表</span>
items1 <span class="token operator">=</span> list<span class="token punctuation">(</span>range<span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">10</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>items1<span class="token punctuation">)</span>    <span class="token comment" spellcheck="true"># [1, 2, 3, 4, 5, 6, 7, 8, 9]</span>
items2 <span class="token operator">=</span> list<span class="token punctuation">(</span><span class="token string">'hello'</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>items2<span class="token punctuation">)</span>    <span class="token comment" spellcheck="true"># ['h', 'e', 'l', 'l', 'o']</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>需要说明的是，列表是一种可变数据类型，也就是说列表可以添加元素、删除元素、更新元素，这一点跟我们上一课讲到的字符串有着鲜明的差别。字符串是一种不可变数据类型，也就是说对字符串做拼接、重复、转换大小写、修剪空格等操作的时候会产生新的字符串，原来的字符串并没有发生任何改变。因此，列表的定义可以总结成这样一句话：<strong>列表是一个有序且可变的容器，在里面可以存放多个不同类型、数据元素可重复的元素。</strong></p>
<ul>
<li>特点<ol>
<li>数据元素的类型可以不相同</li>
<li>以<code>[]</code>包裹，<code>,</code>为分隔符</li>
<li>内部元素有序</li>
<li>内部元素可变</li>
<li>内部元素可重复</li>
</ol>
</li>
</ul>
<h2 id="列表的方法"><a href="#列表的方法" class="headerlink" title="列表的方法"></a>列表的方法</h2><p>Python中为所有的列表类型的数据提供了一批内置方法。</p>
<p>在开始学习列表的内置方法之前，先来做一个字符串和列表的对比：</p>
<ul>
<li><p>字符串，不可变，即：创建好之后内部就无法修改。【独有功能都是新创建一份数据】</p>
<pre class="line-numbers language-python"><code class="language-python">name <span class="token operator">=</span> <span class="token string">"Michael"</span>
data <span class="token operator">=</span> name<span class="token punctuation">.</span>upper<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>name<span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>data<span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
</li>
<li><p>列表，可变，即：创建好之后内部元素可以修改。【独有功能基本上都是直接操作列表内部，不会创建新的一份数据】</p>
<pre class="line-numbers language-python"><code class="language-python">user_list <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token string">"车子"</span><span class="token punctuation">,</span><span class="token string">"房子"</span><span class="token punctuation">]</span>
user_list<span class="token punctuation">.</span>append<span class="token punctuation">(</span><span class="token string">"票子"</span><span class="token punctuation">)</span>

<span class="token keyword">print</span><span class="token punctuation">(</span>user_list<span class="token punctuation">)</span> <span class="token comment" spellcheck="true"># ["车子","房子","票子"]</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
</li>
</ul>
<p>列表中的常见内置方法如下：</p>
<ul>
<li>追加元素<ul>
<li>append()：在原列表中尾部追加值。</li>
<li>extend(iterable)：批量追加, 将一个列表中的元素逐一添加另外一个列表</li>
<li>insert(index, object)：在原列表的指定索引位置插入值</li>
</ul>
</li>
<li>修改元素<ul>
<li>list[index] = value：修改指定索引位置的元素的值为value</li>
</ul>
</li>
<li>删除元素<ul>
<li>remove(value)：在原列表中根据值删除（从左到右找到第一个删除）【慎用，里面没有会报错】</li>
<li>pop(index)：在原列表中根据索引踢出某个元素（根据索引位置删除），返回该元素的值</li>
<li>del list[index]：根据索引删除某个元素</li>
</ul>
</li>
<li>清空表<ul>
<li>clear()：清空原列表</li>
</ul>
</li>
<li>查询<ul>
<li>index(value)：根据值获取索引 找不到会报错</li>
<li>count(value)：根据值获取出现频次</li>
</ul>
</li>
<li>排序<ul>
<li>sort(reverse=False)：排序</li>
<li>reverse()：反转列表</li>
</ul>
</li>
</ul>
<h3 id="添加、删除、修改和清空列表"><a href="#添加、删除、修改和清空列表" class="headerlink" title="添加、删除、修改和清空列表"></a>添加、删除、修改和清空列表</h3><pre class="line-numbers language-python"><code class="language-python">items <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token string">'Python'</span><span class="token punctuation">,</span> <span class="token string">'Java'</span><span class="token punctuation">,</span> <span class="token string">'Go'</span><span class="token punctuation">,</span> <span class="token string">'Kotlin'</span><span class="token punctuation">]</span>

<span class="token comment" spellcheck="true"># 使用append方法在列表尾部添加元素</span>
items<span class="token punctuation">.</span>append<span class="token punctuation">(</span><span class="token string">'Swift'</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>items<span class="token punctuation">)</span>    <span class="token comment" spellcheck="true"># ['Python', 'Java', 'Go', 'Kotlin', 'Swift']</span>
<span class="token comment" spellcheck="true"># 使用insert方法在列表指定索引位置插入元素</span>
items<span class="token punctuation">.</span>insert<span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">,</span> <span class="token string">'SQL'</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>items<span class="token punctuation">)</span>    <span class="token comment" spellcheck="true"># ['Python', 'Java', 'SQL', 'Go', 'Kotlin', 'Swift']</span>
<span class="token comment" spellcheck="true"># 使用extend方法将另一个列表添加该列表之后</span>
items2 <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token string">'C'</span><span class="token punctuation">,</span> <span class="token string">'C++'</span><span class="token punctuation">,</span> <span class="token string">'C#'</span><span class="token punctuation">,</span> <span class="token string">'Vue'</span><span class="token punctuation">]</span>
items<span class="token punctuation">.</span>extend<span class="token punctuation">(</span>items2<span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>items<span class="token punctuation">)</span> <span class="token comment" spellcheck="true"># ['Python', 'Java', 'SQL', 'Go', 'Kotlin', 'Swift', 'C', 'C++', 'C#', 'Vue']</span>

<span class="token comment" spellcheck="true"># 修改指定索引位置的元素</span>
items<span class="token punctuation">[</span><span class="token number">2</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token string">'MySQL'</span> 
items<span class="token punctuation">[</span><span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token string">'React'</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>items<span class="token punctuation">)</span> <span class="token comment" spellcheck="true"># ['Python', 'Java', 'MySQL', 'Go', 'Kotlin', 'Swift', 'C', 'C++', 'C#', 'React']</span>

<span class="token comment" spellcheck="true"># 删除指定的元素  在原列表中根据值删除（从左到右找到第一个删除）【慎用，里面没有会报错】</span>
items<span class="token punctuation">.</span>remove<span class="token punctuation">(</span><span class="token string">'Java'</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>items<span class="token punctuation">)</span>    <span class="token comment" spellcheck="true"># ['Python', 'MySQL', 'Go', 'Kotlin', 'Swift', 'C', 'C++', 'C#', 'React']</span>
<span class="token comment" spellcheck="true"># 删除指定索引位置的元素</span>
items<span class="token punctuation">.</span>pop<span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">)</span>
items<span class="token punctuation">.</span>pop<span class="token punctuation">(</span>len<span class="token punctuation">(</span>items<span class="token punctuation">)</span> <span class="token operator">-</span> <span class="token number">1</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>items<span class="token punctuation">)</span>    <span class="token comment" spellcheck="true"># ['MySQL', 'Go', 'Kotlin', 'Swift', 'C', 'C++', 'C#']</span>

<span class="token comment" spellcheck="true"># 清空列表中的元素</span>
items<span class="token punctuation">.</span>clear<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>items<span class="token punctuation">)</span>    <span class="token comment" spellcheck="true"># []</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>需要提醒大家，在使用<code>remove</code>方法删除元素时，如果要删除的元素并不在列表中，会引发<code>ValueError</code>异常，错误消息是：<code>list.remove(x): x not in list</code>。在使用<code>pop</code>方法删除元素时，如果索引的值超出了范围，会引发<code>IndexError</code>异常，错误消息是：<code>pop index out of range</code>。</p>
<p>从列表中删除元素其实还有一种方式，就是使用Python中的<code>del</code>关键字后面跟要删除的元素，这种做法跟使用<code>pop</code>方法指定索引删除元素没有实质性的区别，但后者会返回删除的元素，前者在性能上略优（<code>del</code>对应字节码指令是<code>DELETE_SUBSCR</code>，而<code>pop</code>对应的字节码指令是<code>CALL_METHOD</code>和<code>POP_TOP</code>）。</p>
<pre class="line-numbers language-python"><code class="language-python">items <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token string">'Python'</span><span class="token punctuation">,</span> <span class="token string">'Java'</span><span class="token punctuation">,</span> <span class="token string">'Go'</span><span class="token punctuation">,</span> <span class="token string">'Kotlin'</span><span class="token punctuation">]</span>
<span class="token keyword">del</span> items<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>items<span class="token punctuation">)</span>    <span class="token comment" spellcheck="true"># ['Python', 'Go', 'Kotlin']</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<h3 id="查找元素位置和次数"><a href="#查找元素位置和次数" class="headerlink" title="查找元素位置和次数"></a>查找元素位置和次数</h3><p>列表类型的<code>index</code>方法可以查找某个元素在列表中的索引位置；因为列表中允许有重复的元素，所以列表类型提供了<code>count</code>方法来统计一个元素在列表中出现的次数。请看下面的代码。</p>
<pre class="line-numbers language-python"><code class="language-python">items <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token string">'Python'</span><span class="token punctuation">,</span> <span class="token string">'Java'</span><span class="token punctuation">,</span> <span class="token string">'Java'</span><span class="token punctuation">,</span> <span class="token string">'Go'</span><span class="token punctuation">,</span> <span class="token string">'Kotlin'</span><span class="token punctuation">,</span> <span class="token string">'Python'</span><span class="token punctuation">]</span>

<span class="token comment" spellcheck="true"># 查找元素的索引位置</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>items<span class="token punctuation">.</span>index<span class="token punctuation">(</span><span class="token string">'Python'</span><span class="token punctuation">)</span><span class="token punctuation">)</span>       <span class="token comment" spellcheck="true"># 0</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>items<span class="token punctuation">.</span>index<span class="token punctuation">(</span><span class="token string">'Python'</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">)</span>    <span class="token comment" spellcheck="true"># 5</span>
<span class="token comment" spellcheck="true"># 注意：虽然列表中有'Java'，但是从索引为3这个位置开始后面是没有'Java'的</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>items<span class="token punctuation">.</span>index<span class="token punctuation">(</span><span class="token string">'Java'</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">)</span><span class="token punctuation">)</span>      <span class="token comment" spellcheck="true"># ValueError: 'Java' is not in list</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>再来看看下面这段代码。</p>
<pre class="line-numbers language-python"><code class="language-python">items <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token string">'Python'</span><span class="token punctuation">,</span> <span class="token string">'Java'</span><span class="token punctuation">,</span> <span class="token string">'Java'</span><span class="token punctuation">,</span> <span class="token string">'Go'</span><span class="token punctuation">,</span> <span class="token string">'Kotlin'</span><span class="token punctuation">,</span> <span class="token string">'Python'</span><span class="token punctuation">]</span>

<span class="token comment" spellcheck="true"># 查找元素出现的次数</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>items<span class="token punctuation">.</span>count<span class="token punctuation">(</span><span class="token string">'Python'</span><span class="token punctuation">)</span><span class="token punctuation">)</span>    <span class="token comment" spellcheck="true"># 2</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>items<span class="token punctuation">.</span>count<span class="token punctuation">(</span><span class="token string">'Go'</span><span class="token punctuation">)</span><span class="token punctuation">)</span>        <span class="token comment" spellcheck="true"># 1</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>items<span class="token punctuation">.</span>count<span class="token punctuation">(</span><span class="token string">'Swfit'</span><span class="token punctuation">)</span><span class="token punctuation">)</span>     <span class="token comment" spellcheck="true"># 0</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h3 id="元素排序和反转"><a href="#元素排序和反转" class="headerlink" title="元素排序和反转"></a>元素排序和反转</h3><p>列表的<code>sort</code>操作可以实现列表元素的排序，而<code>reverse</code>操作可以实现元素的反转，代码如下所示。</p>
<pre class="line-numbers language-python"><code class="language-python">items <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token string">'Python'</span><span class="token punctuation">,</span> <span class="token string">'Java'</span><span class="token punctuation">,</span> <span class="token string">'Go'</span><span class="token punctuation">,</span> <span class="token string">'Kotlin'</span><span class="token punctuation">,</span> <span class="token string">'Python'</span><span class="token punctuation">]</span>

<span class="token comment" spellcheck="true"># 排序</span>
items<span class="token punctuation">.</span>sort<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>items<span class="token punctuation">)</span>    <span class="token comment" spellcheck="true"># ['Go', 'Java', 'Kotlin', 'Python', 'Python']</span>
<span class="token comment" spellcheck="true"># 反转</span>
<span class="token comment" spellcheck="true"># items.sort(reverse=True)</span>
items<span class="token punctuation">.</span>reverse<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>items<span class="token punctuation">)</span>    <span class="token comment" spellcheck="true"># ['Python', 'Python', 'Kotlin', 'Java', 'Go']</span>
<span class="token comment" spellcheck="true"># 注意：排序时内部元素无法进行比较时，程序会报错（尽量数据类型统一）。</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h2 id="列表的运算"><a href="#列表的运算" class="headerlink" title="列表的运算"></a>列表的运算</h2><p>和字符串类型一样，列表也支持拼接、重复、成员运算、索引和切片以及比较运算，这里将列表常见的运算总结如下，请大家参考。</p>
<ul>
<li><code>[] + []</code>, 相加，两个列表相加生成新列表</li>
<li><code>[] * int</code>,相乘，列表*整型 将列表中的元素再创建N份并生成一个新的列表</li>
<li><code>in/not in</code>，成员运算，判断元素是否在列表中</li>
<li><code>len</code>, 获取列表的长度</li>
<li><code>[index]</code>，索引</li>
<li><code>[start:end:step]</code>，切片</li>
<li><code>比较运算</code>：比的是对应索引位置上的元素的大小</li>
</ul>
<p>使用示例</p>
<pre class="line-numbers language-python"><code class="language-python">items1 <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token number">35</span><span class="token punctuation">,</span> <span class="token number">12</span><span class="token punctuation">,</span> <span class="token number">99</span><span class="token punctuation">,</span> <span class="token number">68</span><span class="token punctuation">,</span> <span class="token number">55</span><span class="token punctuation">,</span> <span class="token number">87</span><span class="token punctuation">]</span>
items2 <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token number">45</span><span class="token punctuation">,</span> <span class="token number">8</span><span class="token punctuation">,</span> <span class="token number">29</span><span class="token punctuation">]</span>

<span class="token comment" spellcheck="true"># 列表的拼接</span>
items3 <span class="token operator">=</span> items1 <span class="token operator">+</span> items2
<span class="token keyword">print</span><span class="token punctuation">(</span>items3<span class="token punctuation">)</span>    <span class="token comment" spellcheck="true"># [35, 12, 99, 68, 55, 87, 45, 8, 29]</span>

<span class="token comment" spellcheck="true"># 列表的重复</span>
items4 <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token string">'hello'</span><span class="token punctuation">]</span> <span class="token operator">*</span> <span class="token number">3</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>items4<span class="token punctuation">)</span>    <span class="token comment" spellcheck="true"># ['hello', 'hello', 'hello']</span>

<span class="token comment" spellcheck="true"># 列表的成员运算</span>
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token number">100</span> <span class="token keyword">in</span> items3<span class="token punctuation">)</span>        <span class="token comment" spellcheck="true"># False</span>
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'hello'</span> <span class="token keyword">in</span> items4<span class="token punctuation">)</span>    <span class="token comment" spellcheck="true"># True</span>

<span class="token comment" spellcheck="true"># 获取列表的长度(元素个数)</span>
size <span class="token operator">=</span> len<span class="token punctuation">(</span>items3<span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>size<span class="token punctuation">)</span>                 <span class="token comment" spellcheck="true"># 9</span>

<span class="token comment" spellcheck="true"># 列表的索引</span>
<span class="token comment" spellcheck="true"># 查</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>items3<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span><span class="token punctuation">,</span> items3<span class="token punctuation">[</span><span class="token operator">-</span>size<span class="token punctuation">]</span><span class="token punctuation">)</span>        <span class="token comment" spellcheck="true"># 35 35</span>
items3<span class="token punctuation">[</span><span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token number">100</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>items3<span class="token punctuation">[</span>size <span class="token operator">-</span> <span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">,</span> items3<span class="token punctuation">[</span><span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">)</span>    <span class="token comment" spellcheck="true"># 100 100</span>
<span class="token comment" spellcheck="true"># print(items3[20]) # 报错</span>
<span class="token comment" spellcheck="true"># 改</span>
<span class="token comment" spellcheck="true"># items3[1] = 20 </span>
<span class="token comment" spellcheck="true"># print(items3)  # [35, 12, 99, 68, 55, 87, 45, 8, 29]</span>
<span class="token comment" spellcheck="true"># 删 比较一下这种方法与remove和pop的区别</span>
<span class="token comment" spellcheck="true"># del items[1]</span>
<span class="token comment" spellcheck="true"># print(items3)  # [35, 99, 68, 55, 87, 45, 8, 29]</span>
<span class="token comment" spellcheck="true"># 注意：超出索引范围会报错。</span>
<span class="token comment" spellcheck="true"># 提示：由于字符串是不可变类型，所以他只有索引读的功能，而列表可以进行 读、改、删</span>

<span class="token comment" spellcheck="true"># 列表的切片 也支持读、改、删</span>
<span class="token comment" spellcheck="true"># 读</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>items3<span class="token punctuation">[</span><span class="token punctuation">:</span><span class="token number">5</span><span class="token punctuation">]</span><span class="token punctuation">)</span>          <span class="token comment" spellcheck="true"># [35, 12, 99, 68, 55]</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>items3<span class="token punctuation">[</span><span class="token number">4</span><span class="token punctuation">:</span><span class="token punctuation">]</span><span class="token punctuation">)</span>          <span class="token comment" spellcheck="true"># [55, 87, 45, 8, 100]</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>items3<span class="token punctuation">[</span><span class="token operator">-</span><span class="token number">5</span><span class="token punctuation">:</span><span class="token operator">-</span><span class="token number">7</span><span class="token punctuation">:</span><span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">)</span>    <span class="token comment" spellcheck="true"># [55, 68]</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>items3<span class="token punctuation">[</span><span class="token punctuation">:</span><span class="token punctuation">:</span><span class="token operator">-</span><span class="token number">2</span><span class="token punctuation">]</span><span class="token punctuation">)</span>        <span class="token comment" spellcheck="true"># [100, 45, 55, 99, 35]</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>items3<span class="token punctuation">[</span><span class="token punctuation">:</span><span class="token punctuation">:</span><span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">)</span>        <span class="token comment" spellcheck="true"># 反转列表</span>
<span class="token comment" spellcheck="true"># 改</span>
<span class="token comment" spellcheck="true"># items3[1:3] = [1,10]</span>
<span class="token comment" spellcheck="true"># print(items)  #  [35, 1, 10, 68, 55, 87, 45, 8, 29]</span>
<span class="token comment" spellcheck="true"># 删</span>
<span class="token comment" spellcheck="true"># del items3[1:]</span>
<span class="token comment" spellcheck="true"># print(items)  #  [35]</span>

<span class="token comment" spellcheck="true"># 列表的比较运算</span>
items5 <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">,</span> <span class="token number">4</span><span class="token punctuation">]</span>
items6 <span class="token operator">=</span> list<span class="token punctuation">(</span>range<span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">5</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
<span class="token comment" spellcheck="true"># 两个列表比较相等性比的是对应索引位置上的元素是否相等</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>items5 <span class="token operator">==</span> items6<span class="token punctuation">)</span>    <span class="token comment" spellcheck="true"># True</span>
items7 <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token number">3</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">1</span><span class="token punctuation">]</span>
<span class="token comment" spellcheck="true"># 两个列表比较大小比的是对应索引位置上的元素的大小</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>items5 <span class="token operator">&lt;=</span> items7<span class="token punctuation">)</span>    <span class="token comment" spellcheck="true"># True</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>要注意的是，由于列表是可变类型，所以通过索引操作既可以获取列表中的元素，也可以更新列表中的元素。对列表做索引操作一样要注意索引越界的问题，对于有<code>N</code>个元素的列表，正向索引的范围是<code>0</code>到<code>N-1</code>，负向索引的范围是<code>-1</code>到<code>-N</code>，如果超出这个范围，将引发<code>IndexError</code>异常，错误信息为：<code>list index out of range</code>。</p>
<h2 id="列表元素的遍历"><a href="#列表元素的遍历" class="headerlink" title="列表元素的遍历"></a>列表元素的遍历</h2><p>如果想逐个取出列表中的元素，可以使用<code>for</code>循环的，有以下两种做法。</p>
<p>方法一：</p>
<pre class="line-numbers language-python"><code class="language-python">items <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token string">'Python'</span><span class="token punctuation">,</span> <span class="token string">'Java'</span><span class="token punctuation">,</span> <span class="token string">'Go'</span><span class="token punctuation">,</span> <span class="token string">'Kotlin'</span><span class="token punctuation">]</span>

<span class="token keyword">for</span> index <span class="token keyword">in</span> range<span class="token punctuation">(</span>len<span class="token punctuation">(</span>items<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
    <span class="token keyword">print</span><span class="token punctuation">(</span>items<span class="token punctuation">[</span>index<span class="token punctuation">]</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
<p>方法二：</p>
<pre class="line-numbers language-python"><code class="language-python">items <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token string">'Python'</span><span class="token punctuation">,</span> <span class="token string">'Java'</span><span class="token punctuation">,</span> <span class="token string">'Go'</span><span class="token punctuation">,</span> <span class="token string">'Kotlin'</span><span class="token punctuation">]</span>

<span class="token keyword">for</span> item <span class="token keyword">in</span> items<span class="token punctuation">:</span>
    <span class="token keyword">print</span><span class="token punctuation">(</span>item<span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
<p>讲到这里，我们可以用列表的知识来重构上面“掷色子统计每个点数出现次数”的代码。</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token keyword">import</span> random

counters <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span> <span class="token operator">*</span> <span class="token number">6</span>
<span class="token keyword">for</span> _ <span class="token keyword">in</span> range<span class="token punctuation">(</span><span class="token number">6000</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
    face <span class="token operator">=</span> random<span class="token punctuation">.</span>randint<span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">6</span><span class="token punctuation">)</span> <span class="token comment" spellcheck="true"># face = 5</span>
    counters<span class="token punctuation">[</span>face <span class="token operator">-</span> <span class="token number">1</span><span class="token punctuation">]</span> <span class="token operator">+=</span> <span class="token number">1</span>     <span class="token comment" spellcheck="true"># [0, 0, 0, 0, 1, 0]</span>

<span class="token keyword">for</span> i <span class="token keyword">in</span> range<span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">7</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
    <span class="token keyword">print</span><span class="token punctuation">(</span>f<span class="token string">'点数 {i} 出现了 {counters[i - 1]} 次'</span><span class="token punctuation">)</span>

<span class="token keyword">for</span> i <span class="token keyword">in</span> range<span class="token punctuation">(</span>len<span class="token punctuation">(</span>counters<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
    <span class="token keyword">print</span><span class="token punctuation">(</span>f<span class="token string">'点数 {i + 1} 出现了 {counters[i]} 次'</span><span class="token punctuation">)</span>

<span class="token keyword">for</span> index<span class="token punctuation">,</span> value <span class="token keyword">in</span> enumerate<span class="token punctuation">(</span>counters<span class="token punctuation">)</span><span class="token punctuation">:</span>
    <span class="token keyword">print</span><span class="token punctuation">(</span>f<span class="token string">'点数 {index + 1} 出现了 {value} 次'</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>上面的代码中，我们用<code>counters</code>列表中的六个元素分别表示1到6的点数出现的次数，最开始的时候六个元素的值都是<code>0</code>。接下来用随机数模拟掷色子，如果摇出1点<code>counters[0]</code>的值加<code>1</code>，如果摇出2点<code>counters[1]</code>的值加<code>1</code>，以此类推。大家感受一下，这段代码是不是比之前的代码要简单优雅很多。</p>
<p><strong>切记，循环的过程中对数据进行删除会踩坑</strong></p>
<ul>
<li><p>错误方式：有坑</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token comment" spellcheck="true"># 错误方式， 有坑，结果不是你想要的。</span>
user_list <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token string">"刘德发"</span><span class="token punctuation">,</span> <span class="token string">"范德彪"</span><span class="token punctuation">,</span> <span class="token string">"刘华强"</span><span class="token punctuation">,</span> <span class="token string">'刘尼古拉斯赵四'</span><span class="token punctuation">,</span> <span class="token string">"宋小宝"</span><span class="token punctuation">,</span> <span class="token string">"刘能"</span><span class="token punctuation">]</span>
<span class="token keyword">for</span> item <span class="token keyword">in</span> user_list<span class="token punctuation">:</span>
    <span class="token keyword">if</span> item<span class="token punctuation">.</span>startswith<span class="token punctuation">(</span><span class="token string">"刘"</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
        user_list<span class="token punctuation">.</span>remove<span class="token punctuation">(</span>item<span class="token punctuation">)</span>

<span class="token keyword">print</span><span class="token punctuation">(</span>user_list<span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
</li>
<li><p>正确方式：倒着删除</p>
<pre class="line-numbers language-python"><code class="language-python">user_list <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token string">"刘得发"</span><span class="token punctuation">,</span> <span class="token string">"范德彪"</span><span class="token punctuation">,</span> <span class="token string">"刘华强"</span><span class="token punctuation">,</span> <span class="token string">'刘尼古拉斯赵四'</span><span class="token punctuation">,</span> <span class="token string">"宋小宝"</span><span class="token punctuation">,</span> <span class="token string">"刘能"</span><span class="token punctuation">]</span>
<span class="token keyword">for</span> index <span class="token keyword">in</span> range<span class="token punctuation">(</span>len<span class="token punctuation">(</span>user_list<span class="token punctuation">)</span> <span class="token operator">-</span> <span class="token number">1</span><span class="token punctuation">,</span> <span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
    item <span class="token operator">=</span> user_list<span class="token punctuation">[</span>index<span class="token punctuation">]</span>
    <span class="token keyword">if</span> item<span class="token punctuation">.</span>startswith<span class="token punctuation">(</span><span class="token string">"刘"</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
        user_list<span class="token punctuation">.</span>remove<span class="token punctuation">(</span>item<span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>user_list<span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
</li>
</ul>
<h2 id="列表类型转换"><a href="#列表类型转换" class="headerlink" title="列表类型转换"></a>列表类型转换</h2><p>其他数据类型转化为列表。只需要在外面包裹一层list即可。int、bool无法转换成列表</p>
<pre class="line-numbers language-python"><code class="language-python">list<span class="token punctuation">(</span>其他类型数据<span class="token punctuation">)</span>   <span class="token comment" spellcheck="true"># 其他数据类型可以是str/tuple/dict/set等</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>示例：</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token comment" spellcheck="true"># int、bool无法转换成列表</span>
<span class="token comment" spellcheck="true"># str -> list</span>
name <span class="token operator">=</span> <span class="token string">"张亚飞"</span>
data <span class="token operator">=</span> list<span class="token punctuation">(</span>name<span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># ["张","亚","飞"]</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>data<span class="token punctuation">)</span>
<span class="token comment" spellcheck="true"># tuple -> list</span>
v1 <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token number">11</span><span class="token punctuation">,</span><span class="token number">22</span><span class="token punctuation">,</span><span class="token number">33</span><span class="token punctuation">,</span><span class="token number">44</span><span class="token punctuation">)</span> <span class="token comment" spellcheck="true"># 元组</span>
vv1 <span class="token operator">=</span> list<span class="token punctuation">(</span>v1<span class="token punctuation">)</span>     <span class="token comment" spellcheck="true"># 列表 [11,22,33,44]</span>
<span class="token comment" spellcheck="true"># set -> list</span>
v2 <span class="token operator">=</span> <span class="token punctuation">{</span><span class="token string">"Michael"</span><span class="token punctuation">,</span><span class="token string">"james"</span><span class="token punctuation">,</span><span class="token string">"kobe"</span><span class="token punctuation">}</span> <span class="token comment" spellcheck="true"># 集合</span>
vv2 <span class="token operator">=</span> list<span class="token punctuation">(</span>v2<span class="token punctuation">)</span> <span class="token comment" spellcheck="true"># 列表 ["Michael","james","kobe"]</span>
<span class="token comment" spellcheck="true"># dict -> list</span>
v1 <span class="token operator">=</span> <span class="token punctuation">{</span><span class="token string">'k1'</span><span class="token punctuation">:</span> <span class="token string">'v1'</span><span class="token punctuation">,</span> <span class="token string">'k2'</span><span class="token punctuation">:</span> <span class="token string">'v2'</span><span class="token punctuation">}</span>
v2 <span class="token operator">=</span> list<span class="token punctuation">(</span>v1<span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># ['k1', 'k2']</span>
v3 <span class="token operator">=</span> list<span class="token punctuation">(</span>v1<span class="token punctuation">.</span>keys<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># ['k1', 'k2']</span>
v4 <span class="token operator">=</span> list<span class="token punctuation">(</span>v1<span class="token punctuation">.</span>values<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token comment" spellcheck="true"># ['v1', 'v2']</span>
<span class="token comment" spellcheck="true"># 其他可迭代对象</span>
v1 <span class="token operator">=</span> list<span class="token punctuation">(</span>range<span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h2 id="嵌套列表"><a href="#嵌套列表" class="headerlink" title="嵌套列表"></a>嵌套列表</h2><p>Python语言没有限定列表中的元素必须是相同的数据类型，也就是说一个列表中的元素可以任意的数据类型，当然也包括列表。如果列表中的元素又是列表，那么我们可以称之为嵌套的列表。嵌套的列表可以用来表示表格或数学上的矩阵，例如：我们想保存5个学生3门课程的成绩，可以定义一个保存5个元素的列表保存5个学生的信息，而每个列表元素又是3个元素构成的列表，分别代表3门课程的成绩。但是，一定要注意下面的代码是有问题的。</p>
<pre class="line-numbers language-python"><code class="language-python">scores <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span> <span class="token operator">*</span> <span class="token number">3</span><span class="token punctuation">]</span> <span class="token operator">*</span> <span class="token number">5</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>scores<span class="token punctuation">)</span>    <span class="token comment" spellcheck="true"># [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<p>看上去我们好像创建了一个<code>5 * 3</code>的嵌套列表，但实际上当我们录入第一个学生的第一门成绩后，你就会发现问题来了，我们看看下面代码的输出。</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token comment" spellcheck="true"># 嵌套的列表需要多次索引操作才能获取元素</span>
scores<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span><span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token number">95</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>scores<span class="token punctuation">)</span>    <span class="token comment" spellcheck="true"># [[95, 0, 0], [95, 0, 0], [95, 0, 0], [95, 0, 0], [95, 0, 0]]</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<p>我们不去过多的解释为什么会出现这样的问题，如果想深入研究这个问题，可以通过<a target="_blank" rel="noopener" href="http://www.pythontutor.com/visualize.html">Python Tutor</a>网站的可视化代码执行功能，看看创建列表时计算机内存中发生了怎样的变化，下面的图就是在这个网站上生成的。建议大家不去纠结这个问题，现阶段只需要记住不能用<code>[[0] * 3] * 5]</code>这种方式来创建嵌套列表就行了。那么创建嵌套列表的正确做法是什么呢，下面的代码会给你答案。</p>
<pre class="line-numbers language-python"><code class="language-python">scores <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token punctuation">[</span>0for _ <span class="token keyword">in</span> range<span class="token punctuation">(</span><span class="token number">5</span><span class="token punctuation">)</span><span class="token punctuation">]</span>
scores<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span><span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token number">95</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>scores<span class="token punctuation">)</span>    <span class="token comment" spellcheck="true"># [[95, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<p>对于嵌套的值，可以根据之前学习的索引知识点来进行学习，例如：</p>
<pre class="line-numbers language-python"><code class="language-python">data <span class="token operator">=</span> <span class="token punctuation">[</span> <span class="token string">"谢广坤"</span><span class="token punctuation">,</span><span class="token punctuation">[</span><span class="token string">"海燕"</span><span class="token punctuation">,</span><span class="token string">"赵本山"</span><span class="token punctuation">]</span><span class="token punctuation">,</span><span class="token boolean">True</span><span class="token punctuation">,</span><span class="token punctuation">[</span><span class="token number">11</span><span class="token punctuation">,</span><span class="token number">22</span><span class="token punctuation">,</span><span class="token number">33</span><span class="token punctuation">,</span><span class="token number">44</span><span class="token punctuation">]</span><span class="token punctuation">,</span><span class="token string">"宋小宝"</span> <span class="token punctuation">]</span>

<span class="token keyword">print</span><span class="token punctuation">(</span> data<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span> <span class="token punctuation">)</span> <span class="token comment" spellcheck="true"># "谢广坤"</span>
<span class="token keyword">print</span><span class="token punctuation">(</span> data<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span> <span class="token punctuation">)</span> <span class="token comment" spellcheck="true"># ["海燕","赵本山"]</span>
<span class="token keyword">print</span><span class="token punctuation">(</span> data<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span><span class="token punctuation">[</span><span class="token number">2</span><span class="token punctuation">]</span> <span class="token punctuation">)</span> <span class="token comment" spellcheck="true"># "坤"</span>
<span class="token keyword">print</span><span class="token punctuation">(</span> data<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">[</span><span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">]</span> <span class="token punctuation">)</span> <span class="token comment" spellcheck="true"># "赵本山"</span>

data<span class="token punctuation">.</span>append<span class="token punctuation">(</span><span class="token number">666</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>data<span class="token punctuation">)</span> <span class="token comment" spellcheck="true"># [ "谢广坤",["海燕","赵本山"],True,[11,22,33,44],"宋小宝",666]</span>

data<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">.</span>append<span class="token punctuation">(</span><span class="token string">"谢大脚"</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>data<span class="token punctuation">)</span> <span class="token comment" spellcheck="true"># [ "谢广坤",["海燕","赵本山","谢大脚"],True,[11,22,33,44],"宋小宝",666 ]</span>


<span class="token keyword">del</span> data<span class="token punctuation">[</span><span class="token operator">-</span><span class="token number">2</span><span class="token punctuation">]</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>data<span class="token punctuation">)</span> <span class="token comment" spellcheck="true"># [ "谢广坤",["海燕","赵本山","谢大脚"],True,[11,22,33,44],666 ]</span>


data<span class="token punctuation">[</span><span class="token operator">-</span><span class="token number">2</span><span class="token punctuation">]</span><span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token string">"Michael"</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>data<span class="token punctuation">)</span> <span class="token comment" spellcheck="true"># [ "谢广坤",["海燕","赵本山","谢大脚"],True,[11,"Michael",33,44],666 ]</span>


data<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">:</span><span class="token number">2</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token number">999</span><span class="token punctuation">,</span><span class="token number">666</span><span class="token punctuation">]</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>data<span class="token punctuation">)</span> <span class="token comment" spellcheck="true"># [ "谢广坤",[999,666,"谢大脚"],True,[11,"Michael",33,44],666 ]</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h2 id="列表生成式"><a href="#列表生成式" class="headerlink" title="列表生成式"></a>列表生成式</h2><p>在Python中，列表还可以通过一种特殊的字面量语法来创建，这种语法叫做生成式。它的语法是：</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token punctuation">[</span>exp <span class="token keyword">for</span> iter_var <span class="token keyword">in</span> iterable<span class="token punctuation">]</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<ul>
<li>工作过程<ul>
<li>迭代iterable中的每个元素；</li>
<li>每次迭代都先把结果赋值给iter_var，然后通过exp得到一个新的计算值；</li>
<li>最后把所有通过exp得到的计算值以一个新列表的形式返回。</li>
</ul>
</li>
</ul>
<p>我们给出两段代码，大家可以做一个对比，看看哪一种方式更加简单优雅。</p>
<p>通过<code>for</code>循环为空列表添加元素。</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token comment" spellcheck="true"># 创建一个由1到9的数字构成的列表</span>
items1 <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token punctuation">]</span>
<span class="token keyword">for</span> x <span class="token keyword">in</span> range<span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">10</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
    items1<span class="token punctuation">.</span>append<span class="token punctuation">(</span>x<span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>items1<span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 创建一个由'hello world'中除空格和元音字母外的字符构成的列表</span>
items2 <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token punctuation">]</span>
<span class="token keyword">for</span> x <span class="token keyword">in</span> <span class="token string">'hello world'</span><span class="token punctuation">:</span>
    <span class="token keyword">if</span> x <span class="token operator">not</span> <span class="token keyword">in</span> <span class="token string">' aeiou'</span><span class="token punctuation">:</span>
        items2<span class="token punctuation">.</span>append<span class="token punctuation">(</span>x<span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>items2<span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 创建一个由个两个字符串中字符的笛卡尔积构成的列表</span>
items3 <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token punctuation">]</span>
<span class="token keyword">for</span> x <span class="token keyword">in</span> <span class="token string">'ABC'</span><span class="token punctuation">:</span>
    <span class="token keyword">for</span> y <span class="token keyword">in</span> <span class="token string">'12'</span><span class="token punctuation">:</span>
        items3<span class="token punctuation">.</span>append<span class="token punctuation">(</span>x <span class="token operator">+</span> y<span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>items3<span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>通过生成式创建列表。</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token comment" spellcheck="true"># 创建一个由1到9的数字构成的列表</span>
items1 <span class="token operator">=</span> <span class="token punctuation">[</span>x <span class="token keyword">for</span> x <span class="token keyword">in</span> range<span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">10</span><span class="token punctuation">)</span><span class="token punctuation">]</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>items1<span class="token punctuation">)</span>    <span class="token comment" spellcheck="true"># [1, 2, 3, 4, 5, 6, 7, 8, 9]</span>

<span class="token comment" spellcheck="true"># 创建一个由'hello world'中除空格和元音字母外的字符构成的列表</span>
items2 <span class="token operator">=</span> <span class="token punctuation">[</span>x <span class="token keyword">for</span> x <span class="token keyword">in</span> <span class="token string">'hello world'</span> <span class="token keyword">if</span> x <span class="token operator">not</span> <span class="token keyword">in</span> <span class="token string">' aeiou'</span><span class="token punctuation">]</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>items2<span class="token punctuation">)</span>    <span class="token comment" spellcheck="true"># ['h', 'l', 'l', 'w', 'r', 'l', 'd']</span>

<span class="token comment" spellcheck="true"># 创建一个由个两个字符串中字符的笛卡尔积构成的列表</span>
items3 <span class="token operator">=</span> <span class="token punctuation">[</span>x <span class="token operator">+</span> y <span class="token keyword">for</span> x <span class="token keyword">in</span> <span class="token string">'ABC'</span> <span class="token keyword">for</span> y <span class="token keyword">in</span> <span class="token string">'12'</span><span class="token punctuation">]</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>items3<span class="token punctuation">)</span>    <span class="token comment" spellcheck="true"># ['A1', 'A2', 'B1', 'B2', 'C1', 'C2']</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>下面这种方式不仅代码简单优雅，而且性能也优于上面使用<code>for</code>循环和<code>append</code>方法向空列表中追加元素的方式。可以简单跟大家交待下为什么生成式拥有更好的性能，那是因为Python解释器的字节码指令中有专门针对生成式的指令（<code>LIST_APPEND</code>指令）；而<code>for</code>循环是通过方法调用（<code>LOAD_METHOD</code>和<code>CALL_METHOD</code>指令）的方式为列表添加元素，方法调用本身就是一个相对耗时的操作。对这一点不理解也没有关系，记住“<strong>强烈建议用生成式语法来创建列表</strong>”这个结论就可以了。</p>
<ul>
<li>带过滤功能的列表生成式</li>
</ul>
<pre class="line-numbers language-python"><code class="language-python"><span class="token punctuation">[</span>exp <span class="token keyword">for</span> iter_var <span class="token keyword">in</span> iterable <span class="token punctuation">[</span><span class="token keyword">if</span> exp<span class="token punctuation">]</span><span class="token punctuation">]</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<pre class="line-numbers language-python"><code class="language-python">lists <span class="token operator">=</span> <span class="token punctuation">[</span>i <span class="token keyword">for</span> i <span class="token keyword">in</span> range<span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">)</span> <span class="token keyword">if</span> i <span class="token operator">&lt;</span> <span class="token number">6</span><span class="token punctuation">]</span>

<span class="token keyword">print</span><span class="token punctuation">(</span>lists<span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># [0, 1, 2, 3, 4, 5]</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<ul>
<li>循环嵌套语法格式</li>
</ul>
<pre class="line-numbers language-python"><code class="language-python"><span class="token punctuation">[</span>exp <span class="token keyword">for</span> iter_var_A <span class="token keyword">in</span> iterable_A  <span class="token keyword">for</span> iter_var_B <span class="token keyword">in</span> iterable_B<span class="token punctuation">]</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<pre class="line-numbers language-python"><code class="language-python">L1 <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token string">'香蕉'</span><span class="token punctuation">,</span> <span class="token string">'苹果'</span><span class="token punctuation">,</span> <span class="token string">'橙子'</span><span class="token punctuation">]</span>
L2 <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token string">'可乐'</span><span class="token punctuation">,</span> <span class="token string">'牛奶'</span><span class="token punctuation">]</span>

<span class="token comment" spellcheck="true"># 不使用列表生成式实现</span>
list7 <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token punctuation">]</span>
<span class="token keyword">for</span> x <span class="token keyword">in</span> L1<span class="token punctuation">:</span>
    <span class="token keyword">for</span> y <span class="token keyword">in</span> L2<span class="token punctuation">:</span>
        list7<span class="token punctuation">.</span>append<span class="token punctuation">(</span><span class="token punctuation">(</span>x<span class="token punctuation">,</span> y<span class="token punctuation">)</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 使用列表生成式实现</span>
list8 <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token punctuation">(</span>x<span class="token punctuation">,</span> y<span class="token punctuation">)</span> <span class="token keyword">for</span> x <span class="token keyword">in</span> L1 <span class="token keyword">for</span> y <span class="token keyword">in</span> L2<span class="token punctuation">]</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>list8<span class="token punctuation">)</span>
<span class="token punctuation">[</span><span class="token punctuation">(</span><span class="token string">'香蕉'</span><span class="token punctuation">,</span> <span class="token string">'可乐'</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
 <span class="token punctuation">(</span><span class="token string">'香蕉'</span><span class="token punctuation">,</span> <span class="token string">'牛奶'</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
 <span class="token punctuation">(</span><span class="token string">'苹果'</span><span class="token punctuation">,</span> <span class="token string">'可乐'</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
 <span class="token punctuation">(</span><span class="token string">'苹果'</span><span class="token punctuation">,</span> <span class="token string">'牛奶'</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
 <span class="token punctuation">(</span><span class="token string">'橙子'</span><span class="token punctuation">,</span> <span class="token string">'可乐'</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
 <span class="token punctuation">(</span><span class="token string">'橙子'</span><span class="token punctuation">,</span> <span class="token string">'牛奶'</span><span class="token punctuation">)</span><span class="token punctuation">]</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ul>
<li>用列表生成式生成一副牌【大小王除外】</li>
</ul>
<h2 id="列表生成器"><a href="#列表生成器" class="headerlink" title="列表生成器"></a>列表生成器</h2><pre class="line-numbers language-python"><code class="language-python"><span class="token punctuation">(</span>exp <span class="token keyword">for</span> iter_var <span class="token keyword">in</span> iterable<span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<pre class="line-numbers language-python"><code class="language-python">In <span class="token punctuation">[</span><span class="token number">18</span><span class="token punctuation">]</span><span class="token punctuation">:</span> lists <span class="token operator">=</span> <span class="token punctuation">(</span>i <span class="token keyword">for</span> i <span class="token keyword">in</span> range<span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">)</span><span class="token punctuation">)</span>

In <span class="token punctuation">[</span><span class="token number">19</span><span class="token punctuation">]</span><span class="token punctuation">:</span> lists
Out<span class="token punctuation">[</span><span class="token number">19</span><span class="token punctuation">]</span><span class="token punctuation">:</span> <span class="token operator">&lt;</span>generator object <span class="token operator">&lt;</span>genexpr<span class="token operator">></span> at <span class="token number">0x0000009BD7BC4E08</span><span class="token operator">></span>

In <span class="token punctuation">[</span><span class="token number">20</span><span class="token punctuation">]</span><span class="token punctuation">:</span> lists<span class="token punctuation">.</span>__next__
Out<span class="token punctuation">[</span><span class="token number">20</span><span class="token punctuation">]</span><span class="token punctuation">:</span> <span class="token operator">&lt;</span>method<span class="token operator">-</span>wrapper <span class="token string">'__next__'</span> of generator object at <span class="token number">0x0000009BD7BC4E08</span><span class="token operator">></span>

In <span class="token punctuation">[</span><span class="token number">21</span><span class="token punctuation">]</span><span class="token punctuation">:</span> lists<span class="token punctuation">.</span>__next__<span class="token punctuation">(</span><span class="token punctuation">)</span>
Out<span class="token punctuation">[</span><span class="token number">21</span><span class="token punctuation">]</span><span class="token punctuation">:</span> <span class="token number">0</span>

In <span class="token punctuation">[</span><span class="token number">22</span><span class="token punctuation">]</span><span class="token punctuation">:</span> next<span class="token punctuation">(</span>lists<span class="token punctuation">)</span>
Out<span class="token punctuation">[</span><span class="token number">22</span><span class="token punctuation">]</span><span class="token punctuation">:</span> <span class="token number">1</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h2 id="生成式和生成器的区别"><a href="#生成式和生成器的区别" class="headerlink" title="生成式和生成器的区别"></a>生成式和生成器的区别</h2><p>先看一段代码</p>
<pre class="line-numbers language-python"><code class="language-python">f <span class="token operator">=</span> <span class="token punctuation">[</span>x <span class="token keyword">for</span> x <span class="token keyword">in</span> range<span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">10</span><span class="token punctuation">)</span><span class="token punctuation">]</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>f<span class="token punctuation">)</span>
f <span class="token operator">=</span> <span class="token punctuation">[</span>x <span class="token operator">+</span> y <span class="token keyword">for</span> x <span class="token keyword">in</span> <span class="token string">'ABCDE'</span> <span class="token keyword">for</span> y <span class="token keyword">in</span> <span class="token string">'1234567'</span><span class="token punctuation">]</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>f<span class="token punctuation">)</span>
<span class="token comment" spellcheck="true"># 用列表的生成表达式语法创建列表容器</span>
<span class="token comment" spellcheck="true"># 用这种语法创建列表之后元素已经准备就绪所以需要耗费较多的内存空间</span>
f <span class="token operator">=</span> <span class="token punctuation">[</span>x <span class="token operator">**</span> <span class="token number">2</span> <span class="token keyword">for</span> x <span class="token keyword">in</span> range<span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">1000</span><span class="token punctuation">)</span><span class="token punctuation">]</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>sys<span class="token punctuation">.</span>getsizeof<span class="token punctuation">(</span>f<span class="token punctuation">)</span><span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># 查看对象占用内存的字节数</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>f<span class="token punctuation">)</span>
<span class="token comment" spellcheck="true"># 请注意下面的代码创建的不是一个列表而是一个生成器对象</span>
<span class="token comment" spellcheck="true"># 通过生成器可以获取到数据但它不占用额外的空间存储数据</span>
<span class="token comment" spellcheck="true"># 每次需要数据的时候就通过内部的运算得到数据(需要花费额外的时间)</span>
f <span class="token operator">=</span> <span class="token punctuation">(</span>x <span class="token operator">**</span> <span class="token number">2</span> <span class="token keyword">for</span> x <span class="token keyword">in</span> range<span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">1000</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>sys<span class="token punctuation">.</span>getsizeof<span class="token punctuation">(</span>f<span class="token punctuation">)</span><span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># 相比生成式生成器不占用存储数据的空间</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>f<span class="token punctuation">)</span>
<span class="token keyword">for</span> val <span class="token keyword">in</span> f<span class="token punctuation">:</span>
    <span class="token keyword">print</span><span class="token punctuation">(</span>val<span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>二者区别如下：</p>
<ul>
<li>列表生成式： 会将所有的结果全部计算出来，把结果存放到内存中，如果列表中数据比较多，会占用过多的内存空间，可能导致MemoryError内存错误或者导致程序在运行时出现卡顿的情况。</li>
<li>列表生成器：会创建一个列表生成器对象，不会一次性的把所有结果都计算出来，如果需要序号获取数据，可以使用next（）函数来获取，但要注意，一旦next()函数获取不到数据，会导致出现StopIteration异常错误，可以使用 for循环遍历生成器对象，获取所有数据。</li>
<li>列表生成式可以循环多次，列表生成器只可循环一次。</li>
<li>视情况而定，如果数据量比较大，推荐使用生成器；</li>
</ul>
<h2 id="简单总结"><a href="#简单总结" class="headerlink" title="简单总结"></a>简单总结</h2><p>Python中的列表底层是一个可以动态扩容的数组，列表元素在内存中也是连续存储的，所以可以实现随机访问（通过一个有效的索引获取到对应的元素且操作时间与列表元素个数无关）。我们暂时不去触碰这些底层存储细节以及列表每个方法的渐近时间复杂度（执行这个方法耗费的时间跟列表元素个数的关系），等需要的时候再告诉大家。现阶段，大家只需要知道<strong>列表是容器</strong>，可以<strong>保存各种类型的数据</strong>，<strong>如何对列表数据进行增删改查</strong>就可以了。</p>

            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://zhangyafeii.gitee.io" rel="external nofollow noreferrer">张亚飞</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://zhangyafeii.gitee.io/python/base/di-8-pian-gao-ji-shu-ju-lei-xing-zhi-lie-biao/">https://zhangyafeii.gitee.io/python/base/di-8-pian-gao-ji-shu-ju-lei-xing-zhi-lie-biao/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="https://zhangyafeii.gitee.io" target="_blank">张亚飞</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/Python%E4%B9%8B%E8%B7%AF/">
                                    <span class="chip bg-color">Python之路</span>
                                </a>
                            
                                <a href="/tags/%E9%AB%98%E7%BA%A7%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B/">
                                    <span class="chip bg-color">高级数据类型</span>
                                </a>
                            
                                <a href="/tags/%E5%88%97%E8%A1%A8/">
                                    <span class="chip bg-color">列表</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">

<div id="article-share">
    
    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/medias/reward/alipay.jpg" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/medias/reward/wechat.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>
            
        </div>
    </div>

    
        <link rel="stylesheet" href="/libs/gitalk/gitalk.css">
<link rel="stylesheet" href="/css/my-gitalk.css">

<div class="card gitalk-card" data-aos="fade-up">
    <div class="comment_headling" style="font-size: 20px; font-weight: 700; position: relative; left: 20px; top: 15px; padding-bottom: 5px;">
        <i class="fas fa-comments fa-fw" aria-hidden="true"></i>
        <span>评论</span>
    </div>
    <div id="gitalk-container" class="card-content"></div>
</div>

<script src="/libs/gitalk/gitalk.min.js"></script>
<script>
    let gitalk = new Gitalk({
        clientID: 'b9bf0e29501275f4f23c',
        clientSecret: '1c56bc88fdb7b23ee3712916a38e5e8d1311823a',
        repo: 'github.io',
        owner: 'zhangyafeii',
        admin: "zhangyafeii",
        id: '2020-12-15T15-15-15',
        distractionFreeMode: false  // Facebook-like distraction free mode
    });

    gitalk.render('gitalk-container');
</script>
    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/python/base/di-9-pian-gao-ji-shu-ju-lei-xing-zhi-yuan-zu/">
                    <div class="card-image">
                        
                        <img src="https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=188778581,3875525777&amp;fm=26&amp;gp=0.jpg" class="responsive-img" alt="第9篇：Python高级数据类型之元组">
                        
                        <span class="card-title">第9篇：Python高级数据类型之元组</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            基础数据类型：

int，整数类型（整形）
float，浮点类型（浮点型）
complex,复数类型
bool，布尔类型
str，字符串类型

高级数据类型

list，列表类型
tuple，元组类型
dict，字典类型
set，集合类型

                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2020-12-16
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/Python/" class="post-category">
                                    Python
                                </a>
                            
                            <a href="/categories/Python/base/" class="post-category">
                                    base
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Python%E4%B9%8B%E8%B7%AF/">
                        <span class="chip bg-color">Python之路</span>
                    </a>
                    
                    <a href="/tags/%E9%AB%98%E7%BA%A7%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B/">
                        <span class="chip bg-color">高级数据类型</span>
                    </a>
                    
                    <a href="/tags/%E5%85%83%E7%BB%84/">
                        <span class="chip bg-color">元组</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/python/base/di-7-pian-python-ji-chu-shu-ju-lei-xing/">
                    <div class="card-image">
                        
                        <img src="https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=512325932,1619516313&amp;fm=15&amp;gp=0.jpg" class="responsive-img" alt="第7篇：Python基础数据类型">
                        
                        <span class="card-title">第7篇：Python基础数据类型</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            学习目标：掌握整型、布尔类型、字符串的必备知识。
基础数据类型：

int，整数类型（整形）
float，浮点类型（浮点型）
complex,复数类型
bool，布尔类型
str，字符串类型

高级数据类型：

list，列表类型
tupl
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2020-12-14
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/Python/" class="post-category">
                                    Python
                                </a>
                            
                            <a href="/categories/Python/base/" class="post-category">
                                    base
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Python%E4%B9%8B%E8%B7%AF/">
                        <span class="chip bg-color">Python之路</span>
                    </a>
                    
                    <a href="/tags/%E5%9F%BA%E7%A1%80%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B/">
                        <span class="chip bg-color">基础数据类型</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>


<script>
    $('#articleContent').on('copy', function (e) {
        // IE8 or earlier browser is 'undefined'
        if (typeof window.getSelection === 'undefined') return;

        var selection = window.getSelection();
        // if the selection is short let's not annoy our users.
        if (('' + selection).length < Number.parseInt('120')) {
            return;
        }

        // create a div outside of the visible area and fill it with the selected text.
        var bodyElement = document.getElementsByTagName('body')[0];
        var newdiv = document.createElement('div');
        newdiv.style.position = 'absolute';
        newdiv.style.left = '-99999px';
        bodyElement.appendChild(newdiv);
        newdiv.appendChild(selection.getRangeAt(0).cloneContents());

        // we need a <pre> tag workaround.
        // otherwise the text inside "pre" loses all the line breaks!
        if (selection.getRangeAt(0).commonAncestorContainer.nodeName === 'PRE') {
            newdiv.innerHTML = "<pre>" + newdiv.innerHTML + "</pre>";
        }

        var url = document.location.href;
        newdiv.innerHTML += '<br />'
            + '来源: 飞凡空间<br />'
            + '文章作者: 张亚飞<br />'
            + '文章链接: <a href="' + url + '">' + url + '</a><br />'
            + '本文章著作权归作者所有，任何形式的转载都请注明出处。';

        selection.selectAllChildren(newdiv);
        window.setTimeout(function () {bodyElement.removeChild(newdiv);}, 200);
    });
</script>


<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>

    
<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


<!-- 代码块折行 -->

<style type="text/css">
code[class*="language-"], pre[class*="language-"] { white-space: pre !important; }
</style>

    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            // headingsOffset: -205,
            headingSelector: 'h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>



    <footer class="page-footer bg-color">
    <div class="container row center-align">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            <span id="year">年份</span>
            <a href="https://zhangyafeii.gitee.io" target="_blank">张亚飞</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                class="white-color">344.5k</span>&nbsp;字
            
            
            
            
            
            
            <span id="busuanzi_container_site_pv">
                |&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;<span id="busuanzi_value_site_pv"
                    class="white-color"></span>&nbsp;次
            </span>
            
            
            <span id="busuanzi_container_site_uv">
                |&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;<span id="busuanzi_value_site_uv"
                    class="white-color"></span>&nbsp;人
            </span>
            
            <br>
            
            <span id="sitetime">载入运行时间...</span>
            <script>
                function siteTime() {
                    window.setTimeout("siteTime()", 1000);
                    var seconds = 1000;
                    var minutes = seconds * 60;
                    var hours = minutes * 60;
                    var days = hours * 24;
                    var years = days * 365;
                    var today = new Date();
                    var startYear = "2020";
                    var startMonth = "12";
                    var startDate = "18";
                    var startHour = "12";
                    var startMinute = "12";
                    var startSecond = "12";
                    var todayYear = today.getFullYear();
                    var todayMonth = today.getMonth() + 1;
                    var todayDate = today.getDate();
                    var todayHour = today.getHours();
                    var todayMinute = today.getMinutes();
                    var todaySecond = today.getSeconds();
                    var t1 = Date.UTC(startYear, startMonth, startDate, startHour, startMinute, startSecond);
                    var t2 = Date.UTC(todayYear, todayMonth, todayDate, todayHour, todayMinute, todaySecond);
                    var diff = t2 - t1;
                    var diffYears = Math.floor(diff / years);
                    var diffDays = Math.floor((diff / days) - diffYears * 365);
                    var diffHours = Math.floor((diff - (diffYears * 365 + diffDays) * days) / hours);
                    var diffMinutes = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours) /
                        minutes);
                    var diffSeconds = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours -
                        diffMinutes * minutes) / seconds);
                    if (startYear == todayYear) {
                        document.getElementById("year").innerHTML = todayYear;
                        document.getElementById("sitetime").innerHTML = "本站已安全运行 " + diffDays + " 天 " + diffHours +
                            " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒";
                    } else {
                        document.getElementById("year").innerHTML = startYear + " - " + todayYear;
                        document.getElementById("sitetime").innerHTML = "本站已安全运行 " + diffYears + " 年 " + diffDays +
                            " 天 " + diffHours + " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒";
                    }
                }
                setInterval(siteTime, 1000);
            </script>
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/zhangyafeii" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="https://gitee.com/zhangyafeii" class="tooltipped" target="_blank" data-tooltip="访问我的Gitee" data-position="top" data-delay="50">
        <i class="fab fa-google-plus"></i>
    </a>



    <a href="mailto:zhangyafeii@foxmail.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=1271570224" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 1271570224" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>







    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script src="/js/search.js"></script>
<script type="text/javascript">
$(function () {
    searchFunc("/" + "search.xml", 'searchInput', 'searchResult');
});
</script>
    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>
    <script src="/js/cursor.js"></script>

    <!-- Global site tag (gtag.js) - Google Analytics -->


    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

    

    

    
    <script type="text/javascript" src="/libs/background/ribbon-dynamic.js" async="async"></script>
    
    
    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
